<template>
  <a-modal
    :visible="visible"
    :title="$t('上传对账文件')"
    @cancel="handleCancel"
  >
    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-align="right"
      :label-col-props="{ span: 6 }"
      :wrapper-col-props="{ span: 18 }"
    >
      <a-form-item field="platformId" :label="$t('平台')" :rules="[{ required: true, message: $t('请选择平台') }]">
        <a-select
          v-model="form.platformId"
          :placeholder="$t('请选择平台')"
          allow-clear
        >
          <a-option v-for="item in platformOptions" :key="item.id" :value="item.id">
            {{ item.name }}
          </a-option>
        </a-select>
      </a-form-item>
      <a-form-item field="file" :label="$t('对账文件')" :rules="[{ required: true, message: $t('请选择对账文件') }]">
        <a-space direction="vertical" :size="8" fill>
          <a-space>
            <a-upload
              accept=".xls,.xlsx"
              :show-file-list="true"
              :limit="1"
              :auto-upload="false"
              @change="handleFileChange"
            >
              <template #upload-button>
                <a-button>{{ $t('选择文件') }}</a-button>
              </template>
            </a-upload>
            <a-button type="outline" @click="downloadTemplate">{{ $t('下载模板') }}</a-button>
          </a-space>
          <div class="upload-tip">
            {{ $t('支持.xls,.xlsx格式，请确保文件包含：订单号、设备编号、开始时间、充电电量、实付金额、电费、服务费、优惠金额') }}
          </div>
        </a-space>
      </a-form-item>
    </a-form>
    <template #footer>
      <a-space>
        <a-button @click="handleCancel">{{ $t('取消') }}</a-button>
        <a-button type="primary" :loading="loading" @click="handleSubmit">
          {{ $t('确定') }}
        </a-button>
      </a-space>
    </template>
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { Message } from '@arco-design/web-vue';
import type { FileItem } from '@arco-design/web-vue';
import * as XLSX from 'xlsx';
import { verifyOrders, getPlatformList } from '@/api/order/reconciliation';
import type { OrderVerifyRequestVO, Platform } from '@/api/order/reconciliation/types';

const props = defineProps<{
  visible: boolean;
}>();

const emit = defineEmits(['update:visible', 'success']);

// 加载状态
const loading = ref(false);

// 表单引用
const formRef = ref();

// 平台选项
const platformOptions = ref<Platform[]>([]);

// 获取平台列表
async function fetchPlatformList() {
  try {
    console.log('开始获取平台列表');
    const res = await getPlatformList();
    console.log('平台列表API响应:', res);
    if (res.data && Array.isArray(res.data)) {
      platformOptions.value = res.data.map((item: { id: number; platformName?: string; name?: string }) => ({
        id: item.id,
        name: item.platformName || item.name || '未知平台'
      }));
      console.log('平台列表数据已更新:', platformOptions.value);
    }
  } catch (error) {
    console.error('获取平台列表失败:', error);
    Message.error('获取平台列表失败');
  }
}

onMounted(() => {
  console.log('组件已挂载');
  fetchPlatformList();
});

// 表单数据
const form = reactive({
  platformId: undefined as number | undefined,
  file: null as File | null,
});

// 表单校验规则
const rules = {
  platformId: [
    { required: true, message: '请选择平台' }
  ],
  file: [
    { required: true, message: '请选择文件' }
  ]
};

// 处理文件变化
const handleFileChange = (files: FileItem[]) => {
  if (files.length > 0 && files[0].file) {
    form.file = files[0].file;
  } else {
    form.file = null;
  }
};

// 处理取消
const handleCancel = () => {
  emit('update:visible', false);
  form.platformId = undefined;
  form.file = null;
};

// 处理提交
const handleSubmit = async () => {
  if (!form.file || !form.platformId) {
    Message.warning('请选择平台和文件');
    return;
  }

  loading.value = true;
  try {
    const workbook = await readExcelFile(form.file);
    const sheet = workbook.Sheets[workbook.SheetNames[0]];
    
    // 获取原始数据，保留日期类型
    const rawData = XLSX.utils.sheet_to_json(sheet, { raw: true }) as any[];
    // 获取格式化数据，将日期转为字符串
    const formattedData = XLSX.utils.sheet_to_json(sheet, { raw: false }) as any[];
    
    if (!rawData || rawData.length === 0) {
      Message.error('Excel文件内容为空');
      return;
    }

    const verifyRequests: OrderVerifyRequestVO[] = rawData.map((row: any, index: number) => {
      // 获取对应的格式化行数据
      const formattedRow = formattedData[index] || {};
      let startTime = '';
      
      // 1. 如果原始数据是数字类型（Excel序列号）
      if (typeof row['开始时间'] === 'number') {
        // 使用XLSX工具正确解析Excel日期
        const excelDate = row['开始时间'];
        // 获取格式化后的日期字符串（如果存在）
        const formattedDate = formattedRow['开始时间'];
        
        if (typeof formattedDate === 'string') {
          // 如果已经有格式化的日期字符串，则尝试标准化
          if (formattedDate.includes('/')) {
            // 处理格式如 "2025/3/24 12:32:36" 或 "3/24/25 12:32"
            const chinaFormat = formattedDate.match(/^(\d{4})\/(\d{1,2})\/(\d{1,2})\s+(\d{1,2}):(\d{1,2})(?::(\d{1,2}))?$/);
            const usFormat = formattedDate.match(/^(\d{1,2})\/(\d{1,2})\/(\d{2,4})\s+(\d{1,2}):(\d{1,2})(?::(\d{1,2}))?$/);
            
            if (chinaFormat) {
              // 中式日期格式 "2025/3/24 12:32:36"
              const [_, year, month, day, hour, minute, second] = chinaFormat;
              // 先确保所有部分都有值，并补零
              const formattedYear = year;
              const formattedMonth = month.padStart(2, '0');
              const formattedDay = day.padStart(2, '0');
              const formattedHour = hour.padStart(2, '0');
              const formattedMinute = minute.padStart(2, '0');
              // 明确检查秒是否存在，不存在则使用'00'
              const formattedSecond = (second === undefined || second === '') ? '00' : second.padStart(2, '0');
              
              startTime = `${formattedYear}-${formattedMonth}-${formattedDay} ${formattedHour}:${formattedMinute}:${formattedSecond}`;
              console.log('中式日期转换:', formattedDate, '->', startTime);
            } else if (usFormat) {
              // 美式日期格式 "3/24/25 12:32"
              const [_, month, day, year, hour, minute, second] = usFormat;
              
              // 处理两位数年份，假设20xx年
              let formattedYear = year;
              if (formattedYear.length === 2) {
                formattedYear = `20${formattedYear}`;
              }
              
              // 先确保所有部分都有值，并补零
              const formattedMonth = month.padStart(2, '0');
              const formattedDay = day.padStart(2, '0');
              const formattedHour = hour.padStart(2, '0');
              const formattedMinute = minute.padStart(2, '0');
              // 明确检查秒是否存在，不存在则使用'00'
              const formattedSecond = (second === undefined || second === '') ? '00' : second.padStart(2, '0');
              
              startTime = `${formattedYear}-${formattedMonth}-${formattedDay} ${formattedHour}:${formattedMinute}:${formattedSecond}`;
              console.log('美式日期转换:', formattedDate, '->', startTime);
            } else {
              // 其他未知格式，尝试通过Date对象解析
              try {
                const date = new Date(formattedDate);
                if (!isNaN(date.getTime())) {
                  const year = date.getFullYear();
                  const month = String(date.getMonth() + 1).padStart(2, '0');
                  const day = String(date.getDate()).padStart(2, '0');
                  const hours = String(date.getHours()).padStart(2, '0');
                  const minutes = String(date.getMinutes()).padStart(2, '0');
                  const seconds = String(date.getSeconds()).padStart(2, '0');
                  
                  startTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
                  console.log('通用日期转换:', formattedDate, '->', startTime);
                } else {
                  startTime = formattedDate;
                  console.warn('无法解析的日期格式:', formattedDate);
                }
              } catch (error) {
                startTime = formattedDate;
                console.warn('日期解析错误:', formattedDate, error);
              }
            }
          } else {
            // 如果日期字符串不包含'/'但包含'-'和':'，可能已经是标准格式
            if (formattedDate.includes('-') && formattedDate.includes(':')) {
              // 检查是否缺少秒
              if (!formattedDate.match(/\d{2}:\d{2}:\d{2}/)) {
                // 如果只有时分，没有秒，添加:00
                if (formattedDate.match(/\d{2}:\d{2}$/)) {
                  startTime = `${formattedDate}:00`;
                } else {
                  startTime = formattedDate;
                }
              } else {
                startTime = formattedDate;
              }
            } else {
              startTime = formattedDate;
            }
          }
        } else {
          // 如果没有格式化字符串，则从序列号计算
          // 使用XLSX自带的日期处理功能
          const dateObj = XLSX.SSF.parse_date_code(excelDate);
          if (dateObj) {
            const year = dateObj.y;
            const month = String(dateObj.m).padStart(2, '0');
            const day = String(dateObj.d).padStart(2, '0');
            const hours = String(dateObj.H).padStart(2, '0');
            const minutes = String(dateObj.M).padStart(2, '0');
            const seconds = String(dateObj.S).padStart(2, '0');
            
            startTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
          }
        }
      } else if (typeof row['开始时间'] === 'string') {
        // 2. 如果原始数据是字符串类型
        const dateStr = row['开始时间'];
        if (dateStr.includes('/')) {
          // 处理格式如 "2025/3/24 12:32:36" 或 "3/24/25 12:32"
          const chinaFormat = dateStr.match(/^(\d{4})\/(\d{1,2})\/(\d{1,2})\s+(\d{1,2}):(\d{1,2})(?::(\d{1,2}))?$/);
          const usFormat = dateStr.match(/^(\d{1,2})\/(\d{1,2})\/(\d{2,4})\s+(\d{1,2}):(\d{1,2})(?::(\d{1,2}))?$/);
          
          if (chinaFormat) {
            // 中式日期格式 "2025/3/24 12:32:36"
            const [_, year, month, day, hour, minute, second] = chinaFormat;
            // 先确保所有部分都有值，并补零
            const formattedYear = year;
            const formattedMonth = month.padStart(2, '0');
            const formattedDay = day.padStart(2, '0');
            const formattedHour = hour.padStart(2, '0');
            const formattedMinute = minute.padStart(2, '0');
            // 明确检查秒是否存在，不存在则使用'00'
            const formattedSecond = (second === undefined || second === '') ? '00' : second.padStart(2, '0');
            
            startTime = `${formattedYear}-${formattedMonth}-${formattedDay} ${formattedHour}:${formattedMinute}:${formattedSecond}`;
            console.log('中式日期转换:', dateStr, '->', startTime);
          } else if (usFormat) {
            // 美式日期格式 "3/24/25 12:32"
            const [_, month, day, year, hour, minute, second] = usFormat;
            
            // 处理两位数年份，假设20xx年
            let formattedYear = year;
            if (formattedYear.length === 2) {
              formattedYear = `20${formattedYear}`;
            }
            
            // 先确保所有部分都有值，并补零
            const formattedMonth = month.padStart(2, '0');
            const formattedDay = day.padStart(2, '0');
            const formattedHour = hour.padStart(2, '0');
            const formattedMinute = minute.padStart(2, '0');
            // 明确检查秒是否存在，不存在则使用'00'
            const formattedSecond = (second === undefined || second === '') ? '00' : second.padStart(2, '0');
            
            startTime = `${formattedYear}-${formattedMonth}-${formattedDay} ${formattedHour}:${formattedMinute}:${formattedSecond}`;
            console.log('美式日期转换:', dateStr, '->', startTime);
          } else {
            // 如果日期字符串不包含'/'但包含'-'和':'，可能已经是标准格式
            if (dateStr.includes('-') && dateStr.includes(':')) {
              // 检查是否缺少秒
              if (!dateStr.match(/\d{2}:\d{2}:\d{2}/)) {
                // 如果只有时分，没有秒，添加:00
                if (dateStr.match(/\d{2}:\d{2}$/)) {
                  startTime = `${dateStr}:00`;
                } else {
                  startTime = dateStr;
                }
              } else {
                startTime = dateStr;
              }
            } else {
              startTime = dateStr;
            }
          }
        } else {
          startTime = dateStr;
        }
      } else if (row['开始时间'] instanceof Date) {
        // 3. 如果已经是Date对象
        const date = row['开始时间'];
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');
        
        startTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      }
      
      console.log('原始时间值:', row['开始时间'], '格式化后:', startTime);
      
      // 最后验证并确保时间格式正确
      if (startTime && typeof startTime === 'string') {
        // 如果时间格式中没有秒部分，则添加秒
        const timeRegex = /(\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2})(?::(\d{2}))?/;
        const timeMatch = startTime.match(timeRegex);
        
        if (timeMatch && timeMatch[2] === undefined) {
          // 时间字符串匹配但缺少秒的部分
          startTime = `${timeMatch[1]}:00`;
          console.log('添加秒部分:', startTime);
        }
      }
      
      return {
        orderNo: row['订单号']?.toString() || '',
        pileCode: row['设备编号']?.toString() || '',
        startTime: startTime,
        chargingPower: Number(row['充电电量']) || 0,
        actualAmount: Number(row['实付金额']) || 0,
        electricityFee: Number(row['电费']) || 0,
        serviceFee: Number(row['服务费']) || 0,
        discountAmount: Number(row['优惠金额']) || 0
      };
    });

    // 验证数据
    const invalidData = verifyRequests.some(item => 
      !item.orderNo || !item.pileCode || !item.startTime || !item.chargingPower
    );

    if (invalidData) {
      Message.error('Excel文件格式不正确，请确保包含：订单号、设备编号、开始时间、充电电量、实付金额、电费、服务费、优惠金额');
      return;
    }

    console.log('提交数据:', {
      platformId: form.platformId,
      verifyRequests
    });

    const res = await verifyOrders(form.platformId, verifyRequests);
    console.log('响应结果:', res);
    
    if (res.data) {
      Message.success(res.data);
      emit('success');
      handleCancel();
    } else {
      Message.error('提交失败：未收到有效响应');
    }
  } catch (error: any) {
    console.error('处理Excel文件失败:', error);
    Message.error(error.message || '处理Excel文件失败');
  } finally {
    loading.value = false;
  }
};

// 读取Excel文件
const readExcelFile = (file: File): Promise<XLSX.WorkBook> => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = (e) => {
      try {
        const data = new Uint8Array(e.target?.result as ArrayBuffer);
        const workbook = XLSX.read(data, { type: 'array' });
        resolve(workbook);
      } catch (error) {
        reject(error);
      }
    };
    reader.onerror = (error) => reject(error);
    reader.readAsArrayBuffer(file);
  });
};

// 下载模板
const downloadTemplate = () => {
  // 创建工作簿
  const wb = XLSX.utils.book_new();
  
  // 示例数据
  const exampleData = [
    {
      '订单号': 'ORDER2024030100001',
      '设备编号': 'PILE2024001',
      '开始时间': new Date('2024-03-01T08:30:00'),
      '充电电量': 30.5,
      '实付金额': 45.75,
      '电费': 40.0,
      '服务费': 10.75,
      '优惠金额': 5.0
    },
    {
      '订单号': 'ORDER2024030100002',
      '设备编号': 'PILE2024002',
      '开始时间': new Date('2024-03-01T09:15:00'),
      '充电电量': 25.8,
      '实付金额': 38.7,
      '电费': 34.0,
      '服务费': 9.7,
      '优惠金额': 5.0
    }
  ];

  // 创建工作表
  const ws = XLSX.utils.json_to_sheet(exampleData);
  
  // 设置日期格式
  // 遍历查找'开始时间'列的索引
  const range = XLSX.utils.decode_range(ws['!ref'] || 'A1:H3');
  let dateColIndex = -1;
  
  // 查找标题行中'开始时间'的列索引
  for(let C = range.s.c; C <= range.e.c; ++C) {
    const cell = ws[XLSX.utils.encode_cell({r:0, c:C})];
    if(cell && cell.v === '开始时间') {
      dateColIndex = C;
      break;
    }
  }
  
  // 如果找到了'开始时间'列，设置该列的格式
  if(dateColIndex !== -1) {
    // 为数据行设置日期格式
    for(let R = range.s.r + 1; R <= range.e.r; ++R) {
      const cellRef = XLSX.utils.encode_cell({r:R, c:dateColIndex});
      if(!ws[cellRef]) continue;
      
      ws[cellRef].z = 'yyyy-mm-dd hh:mm:ss';
    }
  }

  // 设置列宽
  const colWidth = [
    { wch: 20 }, // 订单号
    { wch: 15 }, // 设备编号
    { wch: 20 }, // 开始时间
    { wch: 12 }, // 充电电量
    { wch: 12 }, // 实付金额
    { wch: 12 }, // 电费
    { wch: 12 }, // 服务费
    { wch: 12 }  // 优惠金额
  ];
  ws['!cols'] = colWidth;

  // 将工作表添加到工作簿
  XLSX.utils.book_append_sheet(wb, ws, '对账模板');

  // 下载文件
  XLSX.writeFile(wb, '对账文件模板.xlsx');
};
</script>

<style scoped>
.upload-tip {
  color: var(--color-text-3);
  font-size: 14px;
}
</style> 